<template>
  <div class="login-container">
    <!-- 背景视频 -->
    <video autoplay muted loop class="login-bg-video">
      <source src="@/assets/no2.mp4" type="video/mp4">
      您的浏览器不支持视频播放。
    </video>

    <div class="login-card">
      <div class="left-panel">
        <img src="@/assets/dznzs.jpg" alt="颜途地陪" class="login-image" />
      </div>

      <div class="right-panel">
        <div class="login-header">
          <h2>"颜途"地陪旅游服务平台</h2>
          <div class="role-tabs">
            <el-button
                :type="loginForm.role === 'visitor' ? 'primary' : 'default'"
                @click="switchRole('visitor')"
                size="small"
                class="role-button"
            >
              游客登录
            </el-button>
            <el-button
                :type="loginForm.role === 'guide' ? 'primary' : 'default'"
                @click="switchRole('guide')"
                size="small"
                class="role-button"
            >
              地陪登录
            </el-button>
            <el-button
                :type="loginForm.role === 'manager' ? 'primary' : 'default'"
                @click="switchRole('manager')"
                size="small"
                class="role-button"
            >
              管理员登录
            </el-button>
          </div>
        </div>

        <div class="login-form">
          <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef">
            <el-form-item prop="username">
              <el-input
                  v-model="loginForm.username"
                  placeholder="请输入用户名"
                  :prefix-icon="User"
                  maxlength="16"
                  class="login-input"
              />
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                  v-model="loginForm.password"
                  type="password"
                  placeholder="请输入密码"
                  :prefix-icon="Lock"
                  show-password
                  maxlength="16"
                  class="login-input"
              />
            </el-form-item>
            <el-form-item prop="captcha">
              <div class="captcha-container">
                <el-input
                    v-model="loginForm.captcha"
                    placeholder="请输入验证码"
                    :prefix-icon="Key"
                    maxlength="5"
                    class="captcha-input"
                />
                <img
                    :src="captchaImage"
                    @click="refreshCaptcha"
                    alt="验证码"
                    class="captcha-image"
                />
              </div>
            </el-form-item>

            <el-form-item>
              <el-button
                  type="primary"
                  @click="handleLogin"
                  :loading="loading"
                  class="login-button"
              >
                {{ loginButtonText }}
              </el-button>
            </el-form-item>
          </el-form>

          <!-- 注册按钮 -->
          <div v-if="loginForm.role === 'visitor' || loginForm.role === 'guide'" class="register-link">
            <el-button type="text" @click="showRegisterDialog" class="register-button">
              还没有账号？立即注册
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 注册对话框 -->
    <el-dialog
        v-model="registerDialogVisible"
        :title="registerForm.role === 'visitor' ? '游客注册' : '地陪注册'"
        width="500px"
        :before-close="handleRegisterClose"
        class="register-dialog"
    >
      <el-form
          :model="registerForm"
          :rules="registerRules"
          ref="registerFormRef"
          label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
              v-model="registerForm.username"
              placeholder="请输入用户名"
              maxlength="16"
              class="register-input"
          />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
              v-model="registerForm.password"
              placeholder="请输入密码"
              type="password"
              maxlength="10"
              class="register-input"
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
              v-model="registerForm.confirmPassword"
              placeholder="请再次输入密码"
              type="password"
              show-password
              maxlength="20"
              class="register-input"
          />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input
              v-model="registerForm.phone"
              placeholder="请输入手机号"
              maxlength="11"
              class="register-input"
          />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input
              v-model="registerForm.email"
              placeholder="请输入邮箱"
              class="register-input"
          />
        </el-form-item>

        <el-form-item label="邮箱验证码" prop="emailCode">
          <div class="email-code-container">
            <el-input
                v-model="registerForm.emailCode"
                placeholder="请输入邮箱验证码"
                class="email-code-input"
            />
            <el-button
                @click="sendEmailCode"
                :disabled="isSendingCode || countdown > 0"
                :loading="emailCodeLoading"
                class="email-code-button"
            >
              {{ countdown > 0 ? `${countdown}秒后重发` : '发送验证码' }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleRegisterClose" class="dialog-cancel-button">取消</el-button>
          <el-button
              type="primary"
              @click="handleRegister"
              :loading="registerLoading"
              class="dialog-confirm-button"
          >
            注册
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, onMounted, computed, reactive} from 'vue'
import { ElMessage } from 'element-plus'
import { User, Lock, Key } from '@element-plus/icons-vue'
import loginApi from '@/api/login_api.js'
import { useRouter } from 'vue-router'
import register_api from "@/api/register_api.js";

// 获取路由对象
const router = useRouter()

// 确认密码验证
// 放前面是为了验证密码
const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

// 登录表单数据
const loginForm = ref({
  username: '',
  password: '',
  captcha: '',
  key: '',
  role: 'visitor' // 默认为游客
})

const loginFormRef = ref(null)
const captchaImage = ref("")
const loading = ref(false)

// 计算属性：登录按钮文本
const loginButtonText = computed(() => {
  switch (loginForm.value.role) {
    case 'visitor': return '游客登录'
    case 'guide': return '地陪登录'
    case 'manager': return '管理员登录'
    default: return '登录'
  }
})

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
}

onMounted(() => {
  refreshCaptcha()
})

// 加载验证码
const refreshCaptcha = async () => {
  try {
    const res = await loginApi.captcha()
    console.log('验证码响应:', res)

    // 检查响应是否正确
    if (res && typeof res === 'object' && res.key && res.base) {
      loginForm.value.key = res.key
      captchaImage.value = res.base
    } else {
      console.error("验证码数据格式不正确:", res)
      ElMessage.error("验证码加载失败，请重试")
    }
  } catch (error) {
    console.error("加载验证码失败:", error)
    ElMessage.error("加载验证码失败: " + (error.message || "网络错误"))
  }
}

// 切换角色
const switchRole = (role) => {
  loginForm.value.role = role
  loginForm.value.username = ''
  loginForm.value.password = ''
  loginForm.value.captcha = ''
  // 切换角色时刷新验证码
  refreshCaptcha()
}

// 处理登录
const handleLogin = async () => {
  // 表单验证
  if (!loginFormRef.value) return
  const valid = await loginFormRef.value.validate()
  if (!valid) return

  if (!loginForm.value.key) {
    //ElMessage.warning('请先获取验证码')
    await refreshCaptcha()
    return
  }

  loading.value = true
  try {
    // 构造登录数据
    const loginData = {
      username: loginForm.value.username.trim(),
      password: loginForm.value.password,
      captcha: loginForm.value.captcha.trim(),
      key: loginForm.value.key
    }

    let result
    switch (loginForm.value.role) {
      case 'visitor':
        result = await loginApi.visitorLogin(loginData)
        break
      case 'guide':
        result = await loginApi.guideLogin(loginData)
        break
      case 'manager':
        result = await loginApi.managerLogin(loginData)
        break
      default:
        throw new Error('未知角色')
    }

    // 检查登录结果
    console.log('登录结果:', result);
    console.log('result类型:', typeof result);
    console.log('result是否为真值:', !!result);

    if (result) {
      console.log('进入成功分支，准备保存token');
      // result 就是 token 字符串
      localStorage.setItem('token', result)
      localStorage.setItem('userRole', loginForm.value.role)

      console.log('Token已保存:', result);
      console.log('localStorage中的token:', localStorage.getItem('token'));

      // 延迟跳转，确保token保存完成
      setTimeout(() => {
        // 根据角色跳转到不同页面
        switch (loginForm.value.role) {
          case 'visitor':
            router.push('/visitorMain')
            break
          case 'guide':
            router.push('/guideMain')
            break
          case 'manager':
            router.push('/main')
            break
        }
      }, 100)
    } else {
      console.log('进入失败分支，result:', result);
      // 登录失败
      //ElMessage.error('登录失败')
      await refreshCaptcha() // 登录失败后刷新验证码
    }
  } catch (error) {
    console.error('登录错误:', error)
    await refreshCaptcha() // 登录失败后刷新验证码
  } finally {
    loading.value = false
  }
}

//注册
// 注册相关数据
const registerDialogVisible = ref(false)//注册对话框是否可见
const registerFormRef = ref(null)//注册表单的引用
const registerLoading = ref(false)//注册按钮是否正在加载
const emailCodeLoading = ref(false)//邮箱验证码按钮是否正在加载
const isSendingCode = ref(false)//是否正在发送验证码
const countdown = ref(0)//倒计时
let countdownTimer = null//倒计时定时器

// 注册表单数据
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',//确认密码
  phone: '',
  email: '',
  emailCode: '',
  role: 'visitor'
})

// 注册表单验证规则
const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 16, message: '用户名长度应在2-16个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 10, message: '密码长度应在6-10个字符之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请输入确认密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  emailCode: [
    { required: true, message: '请输入邮箱验证码', trigger: 'blur' }
  ]
}

// 显示注册对话框
const showRegisterDialog = () => {
  registerForm.role = loginForm.value.role
  registerDialogVisible.value = true
}

// 发送邮箱验证码
const sendEmailCode = async () => {
  if (!registerForm.email) {
    ElMessage.warning('请输入邮箱')
    return
  }

  // 验证邮箱格式
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(registerForm.email)) {
    ElMessage.warning('请输入正确的邮箱格式')
    return
  }

  emailCodeLoading.value = true
  isSendingCode.value = true
  try {
    const result = await register_api.sendEmailCode(registerForm.email)
    console.log('发送验证码响应:', result)

    if (result && (typeof result === 'string' || (result.code === 200))) {
      ElMessage.success(typeof result === 'string' ? result : (result.msg || '验证码已发送至您的邮箱，请查收'))
      // 启动倒计时
      startCountdown()
    } else {
      ElMessage.error(result?.msg || '发送验证码失败')
    }
  } catch (error) {
    console.error('发送验证码异常:', error)
    ElMessage.error('发送验证码失败: ' + (error.message || '网络错误'))
  } finally {
    emailCodeLoading.value = false
    isSendingCode.value = false
  }
}

// 启动倒计时
const startCountdown = () => {
  countdown.value = 60 * 3
  countdownTimer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(countdownTimer)
    }
  }, 1000)
}

// 处理注册
const handleRegister = async () => {
  if (!registerFormRef.value) return

  try {
    const valid = await registerFormRef.value.validate()
    if (!valid){
      console.log('表单验证失败')
      return
    }
  } catch (validateError){
    console.log(validateError)
    ElMessage.error('请检查表单填写是否正确')
    return
  }

  registerLoading.value = true
  try {
    let result
    if (registerForm.role === 'visitor') {
      // 注册游客
      const registerData = {
        username: registerForm.username,
        password: registerForm.password,
        email: registerForm.email,
        phone: registerForm.phone,
        emailCode: registerForm.emailCode,
      }
      result = await register_api.registerVisitor(registerData)
      console.log(result)
    } else if(registerForm.role === 'guide'){
      // 注册导游
      const registerData = {
        username: registerForm.username,
        password: registerForm.password,
        email: registerForm.email,
        phone: registerForm.phone,
        emailCode: registerForm.emailCode,
      }
      result = await register_api.registerGuide(registerData)
      console.log(result)
    }

    if (result && typeof result === 'string') {
      ElMessage.success(result.data || '注册成功！')
      handleRegisterClose();

      // 注册成功后清空表单
      Object.keys(registerForm).forEach(key => {
        registerForm[key] = ''
      })
    } else {
      ElMessage.error(result?.msg || '注册失败')
    }
  } catch (error) {
    //console.error('注册错误详情:', error)
    ElMessage.error('注册失败: ' + (error.message || '网络错误'))
  } finally {
    registerLoading.value = false
  }
}

// 关闭注册对话框
const handleRegisterClose = () => {
  registerDialogVisible.value = false
  // 重置表单
  if (registerFormRef.value) {
    registerFormRef.value.resetFields()
  }
  // 清空倒计时
  if (countdownTimer) {
    clearInterval(countdownTimer)
    countdown.value = 0
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  position: relative;
  overflow: hidden;
}

.login-card {
  display: flex;
  width: 800px;
  height: 500px;
  background: rgba(255, 255, 255, 0.92);
  border-radius: 15px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
  overflow: hidden;
  z-index: 2;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.left-panel {
  flex: 1;
  background: linear-gradient(135deg, #0c1d40 0%, #1a3a6c 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
}

.left-panel::before {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0) 70%);
  transform: rotate(30deg);
}

.login-image {
  max-width: 90%;
  max-height: 90%;
  object-fit: contain;
  border-radius: 8px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.3);
  z-index: 1;
}

.right-panel {
  flex: 1;
  padding: 30px;
  display: flex;
  flex-direction: column;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  color: #0c1d40;
  margin-bottom: 20px;
  font-size: 24px;
  font-weight: 600;
  letter-spacing: 1px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.role-tabs {
  display: flex;
  justify-content: center;
  gap: 10px;
  flex-wrap: wrap;
}

.role-button {
  border-radius: 20px;
  border: 1px solid #0c1d40;
  transition: all 0.3s ease;
  font-weight: 500;
}

.role-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(12, 29, 64, 0.2);
}

.role-button:active {
  transform: translateY(0);
}

.login-form {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.captcha-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.captcha-input {
  flex: 1;
}

.captcha-image {
  height: 40px;
  cursor: pointer;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.captcha-image:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.login-input,
.register-input {
  border-radius: 8px;
  border: 1px solid #d1d1d1;
  transition: all 0.3s ease;
}

.login-input:focus,
.register-input:focus {
  border-color: #0c1d40;
  box-shadow: 0 0 0 3px rgba(12, 29, 64, 0.1);
}

.login-button {
  width: 100%;
  border-radius: 8px;
  background: linear-gradient(135deg, #0c1d40 0%, #1a3a6c 100%);
  border: none;
  font-weight: 600;
  letter-spacing: 1px;
  height: 42px;
  transition: all 0.3s ease;
}

.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(12, 29, 64, 0.3);
}

.register-link {
  text-align: center;
  margin-top: 15px;
}

.register-button {
  color: #0c1d40;
  font-weight: 500;
  transition: all 0.3s ease;
}

.register-button:hover {
  color: #1a3a6c;
  transform: translateY(-1px);
}

/* 背景视频样式 */
.login-bg-video {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  z-index: 1;
  opacity: 0.9;
}

/* 注册对话框样式 */
.register-dialog {
  border-radius: 15px;
  overflow: hidden;
}

:deep(.register-dialog .el-dialog__header) {
  background: linear-gradient(135deg, #0c1d40 0%, #1a3a6c 100%);
  color: white;
  padding: 20px;
}

:deep(.register-dialog .el-dialog__title) {
  color: white;
  font-weight: 500;
}

.email-code-container {
  display: flex;
  gap: 10px;
}

.email-code-input {
  flex: 1;
}

.email-code-button {
  border-radius: 6px;
  background: linear-gradient(135deg, #0c1d40 0%, #1a3a6c 100%);
  border: none;
  color: white;
  font-weight: 500;
  transition: all 0.3s ease;
}

.email-code-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(12, 29, 64, 0.2);
}

.dialog-cancel-button {
  border-radius: 6px;
  border: 1px solid #d1d1d1;
  color: #666;
  transition: all 0.3s ease;
}

.dialog-cancel-button:hover {
  border-color: #0c1d40;
  color: #0c1d40;
}

.dialog-confirm-button {
  border-radius: 6px;
  background: linear-gradient(135deg, #0c1d40 0%, #1a3a6c 100%);
  border: none;
  font-weight: 500;
  transition: all 0.3s ease;
}

.dialog-confirm-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(12, 29, 64, 0.2);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-card {
    width: 95%;
    height: auto;
    flex-direction: column;
  }

  .left-panel {
    height: 200px;
  }

  .login-image {
    max-width: 80%;
    max-height: 80%;
  }

  .role-tabs {
    flex-direction: column;
    align-items: center;
  }

  .role-button {
    width: 80%;
  }

  .captcha-container {
    flex-direction: column;
    align-items: stretch;
  }

  .email-code-container {
    flex-direction: column;
  }
}
</style>
